import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  optimizeDeps: {
    // 预构建排除重量级库,支持动态导入
    exclude: ['three', 'vanta', 'echarts']
  },
  server: {
    port: 8101,
    host: '0.0.0.0',
    open: true,
    cors: true,
    // 🚀 P0网络修复第五步:优化代理配置,支持15MB医疗图像上传
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        changeOrigin: true,
        secure: false,
        ws: true,
        timeout: 30000, // 30秒超时
        // 关键:设置请求体大小限制为15MB
        bodySizeLimit: '15mb',
        configure: (proxy, _options) => {
          proxy.on('error', (err, req, _res) => {
            console.error('❌ API代理错误:', err.message);
            console.error('请求详情:', {
              method: req.method,
              url: req.url,
              headers: req.headers
            });
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            // 记录关键请求信息(不包含敏感数据)
            console.log('📤 API请求:', req.method, req.url);

            // 添加医疗级请求头
            proxyReq.setHeader('X-Forwarded-For', req.ip || '127.0.0.1');
            proxyReq.setHeader('X-Forwarded-Proto', req.protocol || 'http');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            // 检查大文件响应
            const contentLength = proxyRes.headers['content-length'];
            if (contentLength && parseInt(contentLength) > 5 * 1024 * 1024) { // 5MB以上
              console.log('📦 大文件响应:', `${Math.round(parseInt(contentLength) / 1024 / 1024)}MB`, req.url);
            }

            console.log('✅ API响应:', proxyRes.statusCode, req.url, `耗时: ${Date.now() - req._startTime}ms`);
          });
        }
      },
      '/uploads': {
        target: 'http://localhost:4000',
        changeOrigin: true,
        secure: false,
        timeout: 60000, // 60秒超时,文件上传需要更长时间
        // 关键:静态文件也要支持15MB
        bodySizeLimit: '15mb',
        configure: (proxy, _options) => {
          proxy.on('error', (err, req, _res) => {
            console.error('❌ 文件代理错误:', err.message);
            console.error('请求详情:', {
              method: req.method,
              url: req.url,
              headers: req.headers
            });
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('📤 文件请求:', req.method, req.url);
            proxyReq.setHeader('X-Forwarded-For', req.ip || '127.0.0.1');
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            const contentLength = proxyRes.headers['content-length'];
            if (contentLength) {
              console.log('✅ 文件响应:', `${Math.round(parseInt(contentLength) / 1024)}KB`, req.url);
            }
          });
        }
      }
    }
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    // 生产环境优化
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    rollupOptions: {
      output: {
        // 优化代码分割策略
        manualChunks: {
          // Vue核心库单独分包
          'vue-vendor': ['vue', 'vue-router', 'vuex'],
          // UI库单独分包
          'ui-vendor': ['element-plus', '@element-plus/icons-vue'],
          // 工具库分包
          'utils-vendor': ['axios'],
            // 重量级3D库单独分包(按需加载)
          'three-vendor': ['three'],
          'vanta-vendor': ['vanta'],
          // 图表库单独分包(按需加载)
          'chart-vendor': ['echarts']
        },
        // 优化文件命名
        chunkFileNames: (chunkInfo) => {
          const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/').pop() : 'chunk'
          return `js/[name]-[hash].js`
        },
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.')
          const ext = info[info.length - 1]
          if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
            return `media/[name]-[hash].[ext]`
          }
          if (/\.(png|jpe?g|gif|svg)(\?.*)?$/i.test(assetInfo.name)) {
            return `img/[name]-[hash].[ext]`
          }
          if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
            return `fonts/[name]-[hash].[ext]`
          }
          return `assets/[name]-[hash].[ext]`
        }
      }
    },
    // 代码分割优化
    chunkSizeWarningLimit: 1000,
  }
})